package cn.itcast.web.log;


import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

// 标记为切面
@Aspect
@Component// 实例化，放入IOC容器中，让切面被Spring管理
public class LogAspect {
    @Autowired
    private LogService sysLogService;
    @Autowired
    private HttpSession session;
    @Autowired
    private HttpServletRequest request;

    @Around(value = "execution(* cn.itcast.web.controller.*.*.*(..))")
    public Object save(ProceedingJoinPoint jp) {
        Object result = null;
        try {
            //开始执行的（添加，修改，删除。。。）方法
            result = jp.proceed();
            //===开始：记录日志
            SysLog log = new SysLog();
            //获取登录用户信息
            User user = (User)session.getAttribute("loginUser");
            if(user!=null){
                //将用户信息存入对象中
                log.setUserName(user.getUserName());
                //将企业信息存入对象中
                log.setCompanyId(user.getCompanyId());
                log.setCompanyName(user.getCompanyName());
            }
            //IP地址
            log.setIp(request.getLocalAddr());
            //设置记录时间了
            log.setTime(new Date());
            //getSignature(): 获取当前执行的方法
            String methodName = jp.getSignature().getName();
            //getTarget(): 获取当前执行的方法的对象
            String className = jp.getTarget().getClass().getName();
            //执行的方法名称
            log.setMethod(methodName);
            //执行的类名称
            log.setAction(className);
            sysLogService.save(log);


        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return result;
    }

}
